package com.huang.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author han
 * @since 2022-03-03 11:20:25
 */
public class SyncUtils {

    private final Map<String, ReentrantLock> cacheLock = new ConcurrentHashMap<>();

    public void exec(String key, Runnable statement) {
        ReentrantLock mutex4Key = cacheLock.computeIfAbsent(key, k -> new ReentrantLock(true));
        mutex4Key.lock();
        try {
            statement.run();
        } finally {
            if (mutex4Key.getQueueLength() == 0) {
                cacheLock.remove(key);
            }
            mutex4Key.unlock();

        }
    }

}
